package Demo1;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet({"/dept/list","/dept/modify","/dept/detail","/dept/add","/dept/delete","/dept/edit"})
//@WebServlet("/dept/*")
public class OaServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取servlet路径
        String servletPath = req.getServletPath();
        if("/dept/list".equals(servletPath)) {
            // 如果是list就执行list方法
            doList(req, resp);
        }

        else if(servletPath.equals("/dept/modify")){
              doModify(req,resp); 
        }
        else if (servletPath.equals("/dept/detail")) {
            doDetail(req,resp);
        }
        else if (servletPath.equals("/dept/add")){
            doAdd(req,resp);
        }
        else if(servletPath.equals("/dept/delete")){
                DoDelete(req,resp);
        }
        else if (servletPath.equals("/dept/edit")) {
                doEdit(req,resp);
        }
    }
    private void doEdit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();

        // 获取前端的数据
        String deptno = req.getParameter("deptno");

        // 连接数据库
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        out.println("        <!DOCTYPE html>");
        out.println("<html lang='en'>");
        out.println("<head>");
        out.println("  <meta charset='UTF-8'>");
        out.println("    <meta name='viewport' content='width=device-width, initial-scale=1.0'>");
        out.println("    <title>Edit</title>");
        out.println("    <style>");
        out.println("                table{");
        out.println("            border: 2px solid orange;");
        out.println("            margin:30px auto;");
        out.println("            border-collapse: collapse;");
        out.println("            text-align: center;");
        out.println("     }");
        out.println("        tr,td,th{");
        out.println("            border: 2px solid orange;");
        out.println("      }");
        out.println("    </style>");
        out.println("</head>");
        out.println("<body>");
        out.println("<hr>");





        try {

            connection  = DBUtil.getConnection();
            String sql = "select deptno,dname,loc from dept where deptno = ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,deptno);
            resultSet = preparedStatement.executeQuery();

            //这里的while循环只会执行一次
            while(resultSet.next()){
                String dno = resultSet.getString("deptno");
                String dname = resultSet.getString("dname");
                String loc = resultSet.getString("loc");

                out.println("<h1>修改部门</h1>");
                out.println("<form action='/oa2/dept/modify' method='post'>");
                out.println("               部门号<input type='text' name='deptno' value='"+dno+"' readonly='readonly'><br>");
                out.println("               名称<input type='text' name='dname' value='"+dname+"'><br>");
                out.println("                工作地点<input type='text' name='loc' value='"+loc+"'><br>");
                out.println("   <input type='submit' value='保存'>");
                out.println("    <input type='button' value='后退' onclick='window.history.back()'>");
                out.println("</form>");

            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        out.println("</body>");
        out.println("</html>");

    }

    private void DoDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        resp.setContentType("text/html;charset=UTF-8");

        int count = 0;
        // 获取这里的前端部门编号
        String dno = req.getParameter("deptno");
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = DBUtil.getConnection();

            // 开始事务
            connection.setAutoCommit(false);
            String sql = "delete from dept where deptno = ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, dno);
            count = preparedStatement.executeUpdate();
            connection.commit();
        } catch (SQLException e) {
            // 事务回滚
            if (connection != null) {
                try {
                    connection.rollback();
                } catch (SQLException ex) {
                    e.printStackTrace();
                }
            }

            throw new RuntimeException(e);
        } finally {
            DBUtil.close(connection, preparedStatement, null);
        }
        // 检测是否删除成功 假若这里的count是1那么就是删除成功
        if(count == 1){
            // 删除成功就跳转到listServlet页面.
            // 跳转到path指定路径.
//            req.getRequestDispatcher("/dept/list").forward(req,resp);
            // 重定向的时候要加项目名
            resp.sendRedirect(req.getContextPath()+"/dept/list");
        }else {
            // 删除失败
//            req.getRequestDispatcher("/Delerror.html").forward(req,resp);
            resp.sendRedirect(req.getContextPath()+"/Delerror.html");
        }
    }

    private void doAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        // 获取前端提交的数据
        String Deptno = req.getParameter("deptno");
        String Dname = req.getParameter("dname");
        String Loc = req.getParameter("loc");

        // 向数据库中插入数据
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        // 将deptno化作整数插入数据库
        int dno = Integer.parseInt(Deptno);
        int count = 0;
        String sql = "insert into dept(deptno,dname,loc) values(?,?,?)";
        try {
            connection = DBUtil.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            // 设置值
            preparedStatement.setInt(1,dno);
            preparedStatement.setString(2,Dname);
            preparedStatement.setString(3,Loc);

            // 这里的返回值的值是受影响的行数
            count = preparedStatement.executeUpdate();
            System.out.println(count);

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,preparedStatement,null);
        }
        if(count==1){
            // 成功,跳转到list界面,这里的跳转是不需要写项目名的,默认的根就是项目名
            // 注意这里的转发也是一次请求,这里的代码是post请求,但是list类中是get请求,为了避免报错,在list类中的post方法中调用get方法
            // 重定向可以从根本解决问题.
            req.getRequestDispatcher("/dept/list").forward(req,resp);
        }else {
            //失败
            req.getRequestDispatcher("/Adderror.html").forward(req,resp);
        }
    }

    private void doDetail(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();

        // 做准备工作:
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        out.print("<!DOCTYPE html>");
        out.print("<html lang='en'>");
        out.print("<head>");
        out.print("  <meta charset='UTF-8'>");
        out.print("    <meta name='viewport' content='width=device-width, initial-scale=1.0'>");
        out.print("    <title>Document</title>");
        out.print("    <style>");
        out.print("                table{");
        out.print("            border: 2px solid gray;");
        out.print("            margin:30px auto;");
        out.print("            border-collapse: collapse;");
        out.print("            text-align: center;");
        out.print("        }");
        out.print("        tr,td,th{");
        out.print("            border: 2px solid gray;");


        out.print(" </style>");
        out.print("</head>");
        out.print("<body>");
        out.print("    <!-- 某一条记录的详细信息: -->");
        out.print("    <table width='50%'>");
        out.print("        <tr>");
        out.print("            <th>部门号</th>");
        out.print("            <th>名称</th>");
        out.print("            <th>工作地点</th>");
        out.print("     </tr>");
        out.print("       <tbody>");

        try {
            // 获取前端数据得到的值:
            String dno = req.getParameter("deptno");
            connection = DBUtil.getConnection();
            String sql = "select deptno,dname,loc from dept where deptno = ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,dno);
            resultSet = preparedStatement.executeQuery();
            while(resultSet.next()){
                String deptno = resultSet.getString("deptno");
                String dname = resultSet.getString("dname");
                String loc = resultSet.getString("loc");


                out.print("           <tr>");
                out.print("               <td>"+deptno+"</td>");
                out.print("              <td>"+dname+"</td>");
                out.print("             <td>"+loc+"</td>");
                out.print("            </tr>");


            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DBUtil.close(connection,preparedStatement,resultSet);
        }
        out.print("        </tbody>");
        out.print("   </table>");
        out.print(" <input type='button' value='后退' onclick='window.history.back()'>");
        out.print("</body>");
        out.print("</html>");
    }


    private void doModify(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        // 获取表单中已经修改过的数据
        String deptno = req.getParameter("deptno");
        String dname = req.getParameter("dname");
        String loc = req.getParameter("loc");

        int count = 0;
        // 获取数据库中的数据并将对应的值进行修改
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        String sql = "update dept set dname =?,loc = ? where deptno = ?";

        try {
            connection = DBUtil.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,dname);
            preparedStatement.setString(2,loc);
            preparedStatement.setString(3,deptno);
            count = preparedStatement.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,preparedStatement,null);
        }
        // 检测是否修改成功
        if(count==1){
            // 成功
//            req.getRequestDispatcher("/dept/list").forward(req,resp);

            // 使用重定向的方式.
            try {
                resp.sendRedirect(req.getContextPath()+"/dept/list");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }else{
            // 失败
//            req.getRequestDispatcher("/Modifyerror.html").forward(req,resp);

            try {
                resp.sendRedirect(req.getContextPath()+"/Modifyerror.html");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }
    }


    private void doList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getContextPath();
       //设置响应的数据类型.
        resp.setContentType("text/html;charset=UTF-8");
        req.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        // 获取数据库中的数据
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        out.print("<!DOCTYPE html>");
        out.print("<html lang='en'>");
        out.print("<head>");
        out.print("   <meta charset='UTF-8'>");
        out.print("   <meta name='viewport' content='width=device-width, initial-scale=1.0'>");
        out.print("   <title>List</title>");
        out.print("   <style>");
        out.print("               table{");
        out.print("           border: 2px solid gray;");
        out.print("           margin:30px auto;");
        out.print("           border-collapse: collapse;");
        out.print("           text-align: center;");
        out.print("           height: 150px;");
        out.print("       }");
        out.print("  tr,td,th{");
        out.print("        border: 2px solid gray;");
        out.print("    }");
        out.print(" </style>");

        out.print("<script>");
        out.print("               function del(dno){");
        out.print("           if(window.confirm('亲确定要删除吗?')){");
        out.print("               window.location.href = 'http://localhost:8080"+path+"/dept/delete?deptno='+dno; ");
        out.print("           }");
        out.print("       }");
        out.print("   </script>");

        out.print(" </head>");
        out.print(" <body>");
        out.print("");
        out.print("  <table width='50%' cellspacing='0' cellpadding='0'>");
        out.print("      <caption>部门信息表</caption>");
        out.print("      <thead>");
        out.print("          <tr>");
        out.print("              <th>部门号</th>");out.print("               <th>名称</th>");
        out.print("              <th>工作地点</th>");
        out.print("              <th>操作</th>");
        out.print("          </tr>");
        out.print("      </thead>");
        out.print("      <tbody>");




        try {
            connection = DBUtil.getConnection();
            String sql = "select deptno,dname,loc from dept";
            preparedStatement = connection.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
            while(resultSet.next()){
                // 获取数据库的数据
                String deptno = resultSet.getString("deptno");
                String dname = resultSet.getString("dname");
                String loc = resultSet.getString("loc");

                out.print("          <tr>");
                out.print("             <td>"+deptno+"</td>");
                out.print("               <td>"+dname+"</td>");
                out.print("              <td>"+loc+"</td>");
                out.print("              <td>");
                out.print("                  <a href='javascript:void(0);' onclick='del("+deptno+");'>删除</a>");
                out.print("                   <a href='"+path+"/dept/edit?deptno="+deptno+"'>修改</a>");
                out.print("                   <a href='"+path+"/dept/detail?deptno="+deptno+"'>详情</a>");
                out.print("               </td>");
                out.print("           </tr>");


                System.out.println(deptno);
                System.out.println(dname);
                System.out.println(loc);

            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally{
            // 释放资源
            DBUtil.close(connection,preparedStatement,resultSet);
        }
        out.print("       </tbody>");
        out.print("       <tfoot >");
        out.print("           <tr>");
        out.print("               <td colspan='4' style='font-size: 16px;'><a href='"+path+"/add.html'>新增</a></td>");
        out.print("           </tr>");
        out.print("       </tfoot>");
        out.print("   </table>");
        out.print("</body>");
        out.print("</html>");
    }
}
